<template>
    <div>
      <!-- 头部 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
         @click-left="onClickLeft"
         class="header"
        >
      </van-nav-bar>

      <!-- 下拉刷新 -->
      <van-pull-refresh
        v-model="refreshing"
        success-text="刷新成功"
        @refresh="onRefresh"
        class="resultList"
        >
            <!-- 文章搜索结果列表 -->
            <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
            >
                <ArticleItem v-for="item in searchResultList"
                @click.native="goArticleDetail(item.art_id)"
                :key="item.art_id" :artobj="item" :isShow=false></ArticleItem>
            </van-list>
      </van-pull-refresh>
    </div>
</template>

<script>
import { searchResultAPI } from '@/api'
import ArticleItem from '@/components/ArticleItem.vue'
export default {
  name: 'SearchResult',
  components: {
    ArticleItem
  },
  data () {
    return {
      // 页码
      page: 1,
      // 搜索结果的文章列表
      searchResultList: [],
      // 下拉刷新加载
      refreshing: false,
      // 上拉加载
      loading: false,
      // 是否完成所有数据的加载
      finished: false

    }
  },
  created () {
    this.getSearchResult()
  },
  methods: {
    // 点击返回搜索页
    onClickLeft () {
      this.$router.back()
    },

    // 文章搜索结果列表
    async getSearchResult () {
      this.loading = true
      const { data: res } = await searchResultAPI({
        q: this.$route.params.keywords,
        page: this.page
      })
      // 没有数据了
      if (res.data.results.length === 0) {
        this.finished = true
        return
      }
      // 合并数据
      this.searchResultList = [...this.searchResultList, ...res.data.results]
      this.loading = false
      console.log(this.searchResultList)
    },

    // 上拉加载
    onLoad () {
      this.page++
      this.getSearchResult()
    },

    // 下拉刷新
    onRefresh () {
      // 清空列表数据
      this.searchResultList = []
      // 让刷新加载为false
      this.refreshing = false
      // 页码加1
      this.page++
      // 重新加载数据
      this.getSearchResult()
      this.finished = false
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
    },

    // 跳转到文章详情页
    goArticleDetail (id) {
      this.$router.push(`/detail?id=${id}`)
    }

  }
}
</script>

<style lang="less" scoped>
.van-nav-bar{
    background-color: #007BFF;
    /deep/ .van-icon{
        color:#fff !important;
     }
}
.header{
    position: fixed;
    width: 100%;
}
.resultList{
    padding-top:46px ;
}
/deep/ .van-nav-bar__title{
    color:#fff;
}
</style>
